﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Nyamr.Implementation
{
    class ReducerHost
    {
        public BaseReducer Reducer { get; set; }
        public string Target { get; set; }
        public string Source { get; set; }

        public void Execute()
        {
            var input = Path.Combine(Source, "data");

            var emitter = new Emitter();
            emitter.NextID = 0;
            emitter.Target = Path.Combine(Target, "data");

            var output = new FileStream(Path.Combine(Target, "index.data"), FileMode.CreateNew);
            var log = new StreamWriter(Path.Combine(Target, "log.data"));

            emitter.Index = new StreamWriter(output);

            var index = new StreamReader(Path.Combine(Source, "index.data"), Encoding.UTF8);
            var dictionary = new Dictionary<string, List<string>>();
            while (!index.EndOfStream)
            {
                var key = index.ReadLine();
                var value = Path.Combine(input, index.ReadLine());
                if (!dictionary.ContainsKey(key)) dictionary.Add(key, new List<string>());
                dictionary[key].Add(value);
            }

            foreach (var key in dictionary.Keys)
            {
                var localKey = key;
                var values = 
                    dictionary[localKey].Select(delegate(string path)
                    {
                        var file = new FileStream(path, FileMode.Open);
                        var value = new byte[file.Length];
                        file.Read(value, 0, value.Length);
                        file.Close();
                        return value;
                    });
                try
                {
                    log.WriteLine("Processing of '{0}' started  at {1}", key, DateTime.Now);
                    log.Flush();
                    Reducer.Reduce(localKey, values, emitter);
                    log.WriteLine("Processing of '{0}' finished at {1}", key, DateTime.Now);
                    log.Flush();
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed at '{0}' key & files:", localKey);
                    foreach (var path in dictionary[localKey])
                    {
                        Console.WriteLine("\t'{0}'", path);
                    }
                    throw;
                }
            }

            output.Flush();
            output.Close();
            log.Flush();
            log.Close();

            Reducer.Dispose();
        }

        public void Execute(string key)
        {
            var input = Path.Combine(Source, "data");

            var emitter = new TestEmitter();
            var index = new StreamReader(Path.Combine(Source, "index.data"), Encoding.UTF8);
            var dictionary = new Dictionary<string, List<string>>();
            while (!index.EndOfStream)
            {
                var name = index.ReadLine();
                var value = Path.Combine(input, index.ReadLine());
                if (!dictionary.ContainsKey(name)) dictionary.Add(name, new List<string>());
                dictionary[name].Add(value);
            }

            var values = dictionary[key].Select(delegate(string path)
            {
                var file = new FileStream(path, FileMode.Open);
                var value = new byte[file.Length];
                file.Read(value, 0, value.Length);
                file.Close();
                return value;
            });

            Reducer.Reduce(key, values, emitter);
            Reducer.Dispose();
        }
    }
}
